#include "logindialog.h"
#include "ui_logindialog.h"

#include "../share/configfiles.h"
#include <QFile>
#include <QDataStream>
#include <QMessageBox>
#include <QSettings>

#define LAST_USER_NAEM "LASTUSERNAME"

LoginDialog::LoginDialog(QWidget *parent) :
    curUser(0),
    curGroup(0),
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    init();
}

LoginDialog::~LoginDialog()
{
    qDeleteAll(users);
    qDeleteAll(groups);
    delete ui;
}

void LoginDialog::init()
{
    QFile file(REGISTERED_USERS);
    if (file.open(QIODevice::ReadOnly)) {
        QDataStream in(&file);
        while (!in.atEnd()) {
            User *u = new User;
            in >> *u;
            users << u;
            ui->userIdCombo->addItem(u->name);
        }
        file.close();
    }
    file.setFileName(REGISTERED_GROUPS);
    if (file.open(QIODevice::ReadOnly)) {
        QDataStream in(&file);
        while (!in.atEnd()) {
            Group *g = new Group;
            in >> *g;
            groups << g;
        }
    }

    ui->userIdCombo->setCurrentText(QSettings().value(LAST_USER_NAEM).toString());
    connect(ui->loginButton, SIGNAL(clicked()), this, SLOT(verifyPassword()));
}

void LoginDialog::verifyPassword()
{
    QString userId = ui->userIdCombo->currentText();
    QString pwd = ui->passwordEdit->text();

    bool userFound = false;
    foreach (User *u, users) {
        if (u->name == userId) {
            userFound = true;
            if (u->password == encryptPassword(pwd)) {
                bool groupFound = false;
                foreach (Group *g, groups) {
                    if (u->group == g->name) {
                        curUser = u;
                        curGroup = g;
                        groupFound = true;
                        break;
                    }
                }
                if (!groupFound) {
                    QMessageBox::critical(this, tr("User Login"),
                                          tr("Group of \"%1\" doesnot exist.").arg(userId));
                } else {
                    QSettings().setValue(LAST_USER_NAEM, ui->userIdCombo->currentText());
                    accept();
                }
            } else {
                QMessageBox::critical(this, tr("User Login"), tr("Incorrect password."));
            }
            break;
        }
    }
    if (!userFound) {
        QMessageBox::critical(this, tr("User Login"), tr("User doesnot exist."));
    }
}

bool LoginDialog::userLogin(User &user, Group &group)
{
    LoginDialog dialog;
    if ((QDialog::Accepted == dialog.exec()) &&
            dialog.curUser && dialog.curGroup) {
        user = *dialog.curUser;
        group = *dialog.curGroup;
        return true;
    } else return false;
}
